package com.yupi.springbootinit.controller;

import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.DeleteRequest;
import com.yupi.springbootinit.common.ResultUtils;
import com.yupi.springbootinit.model.dto.qa.QaInspectionReportAddRequest;
import com.yupi.springbootinit.model.dto.qa.QaInspectionReportQueryRequest;
import com.yupi.springbootinit.model.dto.qa.QaInspectionReportUpdateRequest;
import com.yupi.springbootinit.model.entity.QaInspectionReport;
import com.yupi.springbootinit.model.vo.qa.QaInspectionReportDetailVO;
import com.yupi.springbootinit.service.QaInspectionReportService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.mapper.DepartmentMapper;
import com.yupi.springbootinit.model.entity.Department;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.service.UserService;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 检验报告接口
 *
 * @author zhang
 * @date 2024/02/25
 */
@RestController
@RequestMapping("/qa/inspection-report")
public class QaInspectionReportController {

    @Resource
    private QaInspectionReportService qaInspectionReportService;

    @Resource
    private UserService userService;

    @Resource
    private DepartmentMapper departmentMapper;

    // region 增删改查

    /**
     * 创建
     *
     * @param qaInspectionReportAddRequest
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addQaInspectionReport(@RequestBody QaInspectionReportAddRequest qaInspectionReportAddRequest) {
        long newQaInspectionReportId = qaInspectionReportService.addQaInspectionReport(qaInspectionReportAddRequest);
        return ResultUtils.success(newQaInspectionReportId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteQaInspectionReport(@RequestBody DeleteRequest deleteRequest) {
        boolean b = qaInspectionReportService.deleteQaInspectionReport(deleteRequest);
        return ResultUtils.success(b);
    }

    /**
     * 更新
     *
     * @param qaInspectionReportUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateQaInspectionReport(
            @RequestBody QaInspectionReportUpdateRequest qaInspectionReportUpdateRequest,
            HttpServletRequest request) {
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);

        // 调用Service层（增加了权限校验）
        boolean b = qaInspectionReportService.updateQaInspectionReport(qaInspectionReportUpdateRequest, loginUser);
        return ResultUtils.success(b);
    }

    /**
     * 通过任务ID打开/创建检验报告
     *
     * 场景：用户从待办列表点击"生成检验报告"任务
     *
     * @param taskId 任务ID
     * @return 报告ID
     */
    @GetMapping("/openByTask")
    public BaseResponse<Long> openByTask(@RequestParam Long taskId, HttpServletRequest request) {
        // 1. 参数校验
        if (taskId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "任务ID不能为空");
        }

        // 2. 权限校验：只有品质部人员可以创建报告
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null || loginUser.getDepartmentId() == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "未登录或未分配部门");
        }

        Department dept = departmentMapper.selectById(loginUser.getDepartmentId());
        if (dept == null || !"PZ001".equals(dept.getDepartmentCode())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "仅品质部人员可以创建检验报告");
        }

        // 3. 调用Service层创建/获取报告
        Long reportId = qaInspectionReportService.openByTask(taskId, false);

        return ResultUtils.success(reportId);
    }

    /**
     * 获取检验报告详情（包含主尺寸、仪器设备等完整信息）
     *
     * @param id 报告ID
     * @param request
     * @return 报告详情VO
     */
    @GetMapping("/detail")
    public BaseResponse<QaInspectionReportDetailVO> getReportDetail(
            @RequestParam Long id,
            HttpServletRequest request) {
        // 1. 参数校验
        if (id == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "报告ID不能为空");
        }

        // 2. 获取当前登录用户（用于权限判断）
        User loginUser = userService.getLoginUser(request);

        // 3. 调用Service层获取详情
        QaInspectionReportDetailVO detail = qaInspectionReportService.getReportDetail(id, loginUser);

        return ResultUtils.success(detail);
    }


    /**
     * 提交检验报告
     *
     * 功能：
     * 1. 校验必填信息（主尺寸、仪器设备、判定结果等）
     * 2. 更新报告状态为 SUBMITTED
     * 3. 自动完成关联的待办任务
     *
     * @param id 报告ID
     * @param request
     * @return 是否成功
     */
    @PostMapping("/submit")
    public BaseResponse<Boolean> submitReport(@RequestParam Long id, HttpServletRequest request) {
        // 1. 参数校验
        if (id == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "报告ID不能为空");
        }

        // 2. 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "未登录");
        }

        // 3. 权限校验：只有品质部人员可以提交报告
        if (loginUser.getDepartmentId() == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "未分配部门");
        }

        Department dept = departmentMapper.selectById(loginUser.getDepartmentId());
        if (dept == null || !"PZ001".equals(dept.getDepartmentCode())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "仅品质部人员可以提交检验报告");
        }

        // 4. 调用Service层提交报告
        boolean success = qaInspectionReportService.submitReport(
                id,
                loginUser.getId(),
                loginUser.getUserName()
        );

        return ResultUtils.success(success);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<QaInspectionReport> getQaInspectionReportById(long id) {
        QaInspectionReport qaInspectionReport = qaInspectionReportService.getQaInspectionReportById(id);
        return ResultUtils.success(qaInspectionReport);
    }

    /**
     * 获取列表
     *
     * @param qaInspectionReportQueryRequest
     * @return
     */
    @GetMapping("/list")
    public BaseResponse<List<QaInspectionReport>> listQaInspectionReport(QaInspectionReportQueryRequest qaInspectionReportQueryRequest) {
        List<QaInspectionReport> qaInspectionReportList = qaInspectionReportService.listQaInspectionReport(qaInspectionReportQueryRequest);
        return ResultUtils.success(qaInspectionReportList);
    }

    /**
     * 分页获取列表
     *
     * @param qaInspectionReportQueryRequest
     * @return
     */
    @GetMapping("/list/page")
    public BaseResponse<Page<QaInspectionReport>> listQaInspectionReportByPage(QaInspectionReportQueryRequest qaInspectionReportQueryRequest) {
        Page<QaInspectionReport> qaInspectionReportPage = qaInspectionReportService.listQaInspectionReportByPage(qaInspectionReportQueryRequest);
        return ResultUtils.success(qaInspectionReportPage);
    }

    @GetMapping("/export/{id}")
    public ResponseEntity<byte[]> exportReport(@PathVariable Long id, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null || loginUser.getDepartmentId() == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "未登录或未分配部门");
        }
        Department dept = departmentMapper.selectById(loginUser.getDepartmentId());
        if (dept == null || (!"PZ001".equals(dept.getDepartmentCode()) && !"XM001".equals(dept.getDepartmentCode()))) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "请联系管理员申请权限");
        }
        QaInspectionReport report = qaInspectionReportService.getQaInspectionReportById(id);
        if (report == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "检验报告不存在");
        }
        byte[] bytes = qaInspectionReportService.exportReportExcel(id);
        String fileNameBase = (report.getProductName() == null ? "产品" : report.getProductName())
                + "出厂检验报告" + (report.getReportNo() == null ? "" : report.getReportNo()) + ".xlsx";
        String encoded = URLEncoder.encode(fileNameBase, StandardCharsets.UTF_8);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + encoded);
        return ResponseEntity.ok().headers(headers).body(bytes);
    }

    // endregion
}